package org.springframework.samples.countries.web.translate;

import java.util.List;
import java.util.Stack;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import pikes.ecma.Assignment;
import pikes.ecma.ExpressionStatement;
import pikes.ecma.IAssignmentExpression;
import pikes.ecma.Identifier;
import pikes.ecma.Statement;
import pikes.ecma.VariableStatement;

public class AStoreOperation implements ByteCodeOperation {

	protected static final Log translatorLogger = LogFactory.getLog("Translator");

	private int index = -1;

	public AStoreOperation(int index) {
		this.index = index;
	}

	public void execute(int numberOfParameters, Stack<Object> stack, List<String> localVariables) {
		translatorLogger.info("ASTORE " + index);

		Object ref = stack.pop();
		IAssignmentExpression iae = (IAssignmentExpression) ref;

		Statement statement = null;
		if (numberOfParameters > 0) {
			if (index > (numberOfParameters + 1)) {
				statement = new VariableStatement(localVariables.get(index), iae);
			}
			else {
				statement = new ExpressionStatement(new Assignment(new Identifier(localVariables.get(index)), iae));
			}
		}
		else {
			statement = new VariableStatement(localVariables.get(index), iae);
		}

		stack.push(statement);
	}

	@Override
	public String toString() {
		return "astore " + index;
	}

}
